package com.selftool.util;

import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;

public class HttpConnection {
    /**
     * doPost：	doPost方法
     *
     * @param json
     * @param url
     * @return
     * @throws Exception String	TODO（参数说明）
     *                   创  建  人 ：CYQ
     *                   创建时间：2022年5月19日
     */
    public static String doPost(String url, String json, Map<String, String> head) throws Exception {

        BufferedReader in = null;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        HttpURLConnection httpURLConnection = null;
        try {
            if (url == null || url.isEmpty()) {
                throw new Exception("URL不能为空！");
            }
            URL adress = new URL(url);
            // 创建连接 测试
            httpURLConnection = (HttpURLConnection) adress.openConnection();
            // 设置请求的内容类型
            httpURLConnection.setRequestProperty("x-zop-ns", "budget");
            httpURLConnection.setRequestProperty("accept", "*/*");
            httpURLConnection.setRequestProperty("connection", "Keep-Alive");
            httpURLConnection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            httpURLConnection.setRequestProperty("Content-Type", "application/json");

            httpURLConnection.setRequestProperty("User-Agent", "PostmanRuntime/7.32.2");
            httpURLConnection.setRequestProperty("Accept", "*/*");
            httpURLConnection.setRequestProperty("Accept-Encoding", "gzip, deflate, br");
            httpURLConnection.setRequestProperty("Connection", "keep-alive");
            httpURLConnection.setConnectTimeout(30000000);
            httpURLConnection.setReadTimeout(30000000);
            //追加请求头
            if (head != null && head.size() > 0) {
                for (String key : head.keySet()) {
                    httpURLConnection.setRequestProperty(key, head.get(key));
                }
            }
            // 设置发送数据
            httpURLConnection.setDoOutput(true);
            // 设置接受数据
            httpURLConnection.setDoInput(true);
            httpURLConnection.setUseCaches(false);
            // 发送数据,使用输出流
            outputStream = httpURLConnection.getOutputStream();
            // 发送的soap协议的数据
            String content = json.toString();
            // 发送数据
            outputStream.write(content.getBytes("UTF-8"));
            // 接收数据
            inputStream = httpURLConnection.getInputStream();
            in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = in.readLine()) != null)
                buffer.append(line);
            String result = buffer.toString();
            outputStream.flush();
            outputStream.close();
            try {
                in.close();
                httpURLConnection.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
                throw new Exception(e.getMessage() + e.getCause());
            }
            return result;
        } catch (Exception e) {
            throw new Exception("doPost异常," + e.getMessage() + e.getCause());
        }
    }


    public static byte[] getFile(String url_str) {
        try {
            // 创建URL对象
            URL url = new URL(url_str);
            // 打开连接
            URLConnection connection = url.openConnection();
            // 获取资源文件流，读取文件流
            InputStream stream = connection.getInputStream();
            byte[] bytes = read(stream);
            return bytes;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static byte[] read(InputStream inputStream) throws IOException {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int num = inputStream.read(buffer);
            while (num != -1) {
                baos.write(buffer, 0, num);
                num = inputStream.read(buffer);
            }
            baos.flush();
            return baos.toByteArray();
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
    }

    /** 访问HTTPS请求时绕过SSL验证 **/
    public static byte[] getFiles(String url_str) {
        try {
            // 创建URL对象
            URL url = new URL(url_str);
            // 打开连接
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();

            // 创建信任所有证书的TrustManager
            TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
                @Override
                public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {}
                @Override
                public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {}
            } };

            // 安装信任所有证书的TrustManager
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

            // 创建所有主机名的验证器
            HostnameVerifier allHostsValid = new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    // TODO Auto-generated method stub
                    return true; // 不验证主机名
                }
            };
            HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
            // 获取资源文件流，读取文件流
            InputStream stream = connection.getInputStream();
            byte[] bytes = read(stream);
            return bytes;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 保存临时文件
     *
     * @param fileName  文件名
     * @param bs  文件流
     * @return  返回文件保存的路径
     */
    public static String SaveTempFile(String filepath, byte[] bs) throws Exception {
        FileOutputStream out = null;
        try {
            File file = new File(filepath);
            out = new FileOutputStream(file);
            out.write(bs,0,bs.length);
        } catch (FileNotFoundException e) {
            throw new Exception("附件下载异常,"+e.getMessage());
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return filepath;
    }
}
